import DivideLine from '@/components/Divider';
import TButton, { DelButton } from '@/components/TButton';
import { PLAN_STAGE } from '@/const';
import { Collapse, DatePicker, Input, message, Popover } from 'antd';
import moment from 'moment';
import { useMemo } from 'react';
import { PlanStageT, PlanT } from '../..';
import Stage from '../Stage';
import './index.less';

const { Panel } = Collapse;

const { RangePicker } = DatePicker;

interface IProps {
  item: PlanT;
  onEditStage: (stage: PlanStageT, field: string, v: any) => void;
  onRemoveStage: (stage: PlanStageT) => void;
  onChangeStageStatus: (stage: PlanStageT) => void;
  onCreateStage: (preIndex: number) => void; // preIndex代表插到那个元素前
}

const PlanItem = (props: IProps) => {
  const {
    item,
    onCreateStage,
    onRemoveStage,
    onEditStage,
    onChangeStageStatus,
  } = props;

  const currentStage = useMemo(() => {
    return item.stages.find((i) => i.status === PLAN_STAGE.DOING);
  }, [item]);

  const planStartTime = useMemo<moment.Moment | ''>(() => {
    let startTime: moment.Moment | '' = '';
    item.stages.forEach((i) => {
      if (i.startTime !== '' && startTime === '') {
        startTime = i.startTime;
      } else if (startTime !== '' && i.startTime !== '') {
        startTime = startTime.isBefore(i.startTime) ? startTime : i.startTime;
      }
    });
    return startTime;
  }, [item]);

  const planLastTime = useMemo(() => {
    if (!planStartTime) {
      return '';
    }
    return moment().diff(planStartTime, 'days');
  }, [item, planStartTime]);

  const currentProgress = useMemo(() => {
    let index = 0;
    for (const s of item.stages) {
      if (s.status === PLAN_STAGE.DONE) {
        index++;
      } else {
        break;
      }
    }
    return index;
  }, [currentStage, item]);

  const getDisplayDate = (i: PlanStageT) => {
    if (!i.startTime) {
      return '未开始';
    }
    if (!i.finishTime) {
      return i.startTime.format('Y-M-D HH:mm') + '至今';
    } else {
      return (
        i.startTime.format('Y-M-D HH:mm') +
        '  至  ' +
        i.finishTime.format('Y-M-D HH:mm')
      );
    }
  };

  const renderEditor = (i: PlanStageT, index: number) => {
    return (
      <div className="col-flex-container" style={{ width: '300px' }}>
        <Input.Search
          defaultValue={i.name}
          style={{ marginBottom: '10px' }}
          size="small"
          allowClear
          enterButton="确认"
          onSearch={(v) => {
            if (v !== '') {
              onEditStage(i, 'name', v);
            } else {
              message.warn('不可为空');
            }
          }}
        />
        <RangePicker
          getPopupContainer={(t) => t}
          defaultValue={[i.startTime || moment(), i.finishTime || moment()]}
          showTime
          size="small"
          style={{ marginBottom: '10px' }}
          onChange={(v) => {
            onEditStage(i, 'time', v);
          }}
        />
        <TButton
          plain
          fullWidth
          style={{ marginBottom: '4px' }}
          onClick={() => {
            onCreateStage(index + 1);
          }}
        >
          插入阶段
        </TButton>
        <DelButton
          onRemove={() => onRemoveStage(i)}
          fullWidth
          style={{ height: '24px' }}
        />
      </div>
    );
  };

  const renderStages = () => {
    return (
      <>
        {item.stages.length ? (
          <>
            {item.stages.map((i, index) => (
              <Stage
                status={i.status}
                isLast={index === item.stages.length - 1}
                content={
                  <Popover
                    content={renderEditor(i, index)}
                    trigger="click"
                    getPopupContainer={(t) => t}
                    placement="right"
                  >
                    <div>
                      <div>{i.name}</div>
                      <div className="stage-desc">{getDisplayDate(i)}</div>
                    </div>
                  </Popover>
                }
                key={i.name}
                onFinish={() => onChangeStageStatus(i)}
              />
            ))}
            <DivideLine bottom={10} />
          </>
        ) : (
          <></>
        )}

        <Stage
          status={PLAN_STAGE.NO_START}
          isLast
          content={
            <TButton onClick={() => onCreateStage(item.stages.length)}>
              新增
            </TButton>
          }
        />
      </>
    );
  };

  return (
    <div className="col-4-lg col-6-md col-12-sm">
      <div className="plan-item__container ">
        <div className="plan-item__stages">
          <div className="plan-item__info">
            <label>描述</label>
            <span>{item.desc || '无'}</span>
          </div>
          <div className="plan-item__info">
            <label>计划开始时间</label>
            <span>
              {planStartTime ? planStartTime.format('Y-M-D HH:mm') : '尚未开始'}
            </span>
          </div>
          <div className="plan-item__info">
            <label>计划进行时间</label>
            <span>
              {planLastTime !== '' ? `${planLastTime}天` : '尚未开始'}
            </span>
          </div>
          {renderStages()}
        </div>
      </div>
    </div>
  );
};

export default PlanItem;
